<?php

/**
 * 跑鞋类
 */
class gearModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }

    public function updateGearSetInfoByGid(array $gearSetInfo)
    {
        return $this->db->insertRow('r_gear', $gearSetInfo, 2);
    }

    public function getGearSetInfoByGid($gid)
    {
        $result = $this->db->getRowTable('r_gear', array('gearId', 'name', 'shortDesc', 'relate_content', 'images', 'possess', 'likes', 'addTime','viewCounts','likes'), "gearId='{$gid}'");

        if($result)
        {
            $images = json_decode($result['images']);
            $result['img'] = $images[0];
        }

        return $result;
    }

    public function setGearSetTop($gid, $top = 1)
    {
        return $this->db->update("update r_gear set possess='{$top}' where gearId='{$gid}' and type=1");
    }

    public function setGearSetHide($gid)
    {
        return $this->db->update("update r_gear set isShow=0 where gearId='{$gid}' and type=1");
    }

   /**
    * 更新跑鞋里程 
    * @param int $gid 
    */
    public function setGearMileage($gid, $mileage, $uid)
    {
        return $this->db->update("update r_gear_comment set mileage='{$mileage}' where gearId='{$gid}' and uid = {$uid}");
    }

    /**
     * 通过装备表数据类型获取装备列表并排序
     * @param string $type
     * @param string $order
     * @param integer $page
     * @param integer $num
     * @return array
     */
    public function getGearListByType($type, $order, $page = 1, $num = 10)
    {
        $result = array('count' => 0, 'pages' => 0, 'page' => $page, 'data' => array());
        $countSql = $dataSql = NULL;

        switch($type)
        {
            case 'all':
                $countSql = 'select count(1) from r_gear where isShow=1';

                switch($order)
                {
                    case 'new':
                        $dataSql = 'select * from r_gear where isShow=1 order by addTime desc';
                        break;
                    
                    case 'hot':
                        $dataSql = 'select *,comments+likes order_num from r_gear where isShow=1 order by order_num desc';
                        break;

                    case 'best':
                        $dataSql = 'select * from r_gear where isShow=1 order by updatetime desc';
                        break;

                }

                break;

            case 'gearNews':
                $countSql = 'select count(1) from r_gear where type=3 and isShow=1';

                switch($order)
                {
                    case 'new':
                        $dataSql = 'select * from r_gear where type=3 and isShow=1 order by addTime desc';
                        break;
                    
                    case 'hot':
                        $dataSql = 'select a.*,b.loves from r_gear a left join r_news b on b.news_id=a.relate_id where a.type=3 and a.isShow=1 order by b.loves desc';
                        break;

                    case 'best':
                        $dataSql = 'select * from r_gear where type=3 and isShow=1 order by updatetime desc';
                        break;
                }

                break;

            case 'gearSet':
                $countSql = 'select count(1) from r_gear where type=1 and isShow=1';

                switch($order)
                {
                    case 'new':
                        $dataSql = 'select * from r_gear where type=1 and isShow=1 order by possess desc,addTime desc';
                        break;
                    
                    case 'hot':
                        $dataSql = 'select * from r_gear where type=1 and isShow=1 order by possess desc,likes desc,addTime desc';
                        break;
                }

                break;

            case 'gearEval':
                $countSql = 'select count(1) from r_gear where type=2 and isShow=1';

                switch($order)
                {
                    case 'new':
                        $dataSql = 'select * from r_gear where type=2 and isShow=1 order by addTime desc';
                        
                        break;
                    
                    case 'hot':
                        $dataSql = 'select *,comments+likes order_num from r_gear where type=2 and isShow=1 order by order_num desc';
                        
                        break;

                    case 'best':
                        $dataSql = 'select * from r_gear where type=2 and isShow=1 order by updatetime desc';

                        break;

                }

                break;

            case 'gearHot':
                $countSql = 'select count(1) from r_gear where isShow=1';
                $dataSql = 'select *,comments+likes order_num from r_gear where isShow=1 order by order_num desc';

                break;


            case 'gearNew':
                $countSql = 'select count(1) from r_gear where isShow=1';
                $dataSql = 'select * from r_gear where isShow=1 order by publishTime desc';

                break;
        }

        $result['count'] = $this->db->getOne($countSql);

        if($result['count'])
        {
            $result['pages'] = ceil($result['count'] / $num);
            $begin = ($page - 1) * $num;
            $dataSql .= " limit {$begin},{$num}";

            $result['data'] = $this->db->getAll($dataSql);

            $bbs_mod = $this->base->load('bbs');
            if($result['data'])
            {
                foreach($result['data'] as $rk => $gear)
                {
                    $gear['images'] = json_decode($gear['images'],true);
                    $gear['img'] = !empty($gear['images'][0]) ? $gear['images'][0] : '';
                    $result['data'][$rk]['img'] = $gear['img'];
                    $result['data'][$rk]['addTime'] = date('m-d', $gear['addTime']);
                    $result['data'][$rk]['possess'] = intval($gear['possess']);

                    if(in_array($gear['type'], array(2, 3)))
                    {
                         $relateContent = json_decode($gear['relate_content'], TRUE);
                         $userInfo = !empty($relateContent['uid']) ? $this->base->load('client')->getUserInfo($relateContent['uid']) : array();
                         $result['data'][$rk]['relate_content'] = $userInfo;
                    }

                    if(in_array($gear['type'], array('2', '3')) && in_array($type, array('all', 'gearNews', 'gearEval')))
                    {
                        $result['data'][$rk]['relate_content']['loves'] = 0;
                        $result['data'][$rk]['relate_content']['total_comment'] = 0;

                        //$bbsInfo = $this->db->getRowTable('r_news', array('loves', 'total_comment'), "news_id='{$gear['relate_id']}'");
                        $bbsInfo = $bbs_mod->getPostInfo($gear['relate_id']);

                        if($bbsInfo)
                        {
                            $result['data'][$rk]['relate_content']['tag'] = $bbsInfo['tag'];
                            $result['data'][$rk]['relate_content']['loves'] = $bbsInfo['loves'];
                            $result['data'][$rk]['relate_content']['total_comment'] = $bbsInfo['total_comment'];
                        }
                    }
                }
            }
        }

        return $result;
    }

    public function getTopSetList()
    {
        $sql="select gearId,name,shortDesc,images,likes,viewCounts from r_gear where type=1 and isShow=1 and possess = 1 limit 3" ;
        $result= $this->db->getAll($sql);
        if(!$result){
            return $result;
        }
        foreach($result as &$row){
            if(!$row['images']){
                continue;
            }
            $row['images'] = json_decode($row['images'],true);
        }
        return $result;
    }

    /**
     * 装备信息
     * @var array
     */
    public function getGearInfo($gearId, $thumbImg = true, $update = false)
    {
        $gearInfos = array();

        $isOne = !is_array($gearId);
        $gearIds = !is_array($gearId) ? array($gearId) : $gearId;
        
        foreach ($gearIds as $gearId)
        {
            $gearInfo = $this->redis->hgetAll(REDIS_PREFIX.'GearInfo_'.$gearId);

            if(!$gearInfo || !$update)
            {
                $gearInfo = $this->db->getRow("select * from r_gear where gearId = '{$gearId}'");

                if(!empty($gearInfo))
                {
                    $this->redis->hmset(REDIS_PREFIX.'GearInfo_'.$gearId, $gearInfo);
                    $this->redis->expire(REDIS_PREFIX.'GearInfo_'.$gearId,180);
                }
            }

            if(empty($gearInfo))
            {
                $gearInfo = array();
            }
            else
            {
                $gearInfo['name'] = stripslashes($gearInfo['name']);
                $gearInfo['price'] = number_format($gearInfo['price'], 2, '.', '');
                $gearInfo['likes'] = !isset($gearInfo['likes']) ? '0' : $gearInfo['likes'];
                $gearInfo['brand'] = $this->getBrandInfo($gearInfo['brand']);
                $gearInfo['evaluate'] = $this->getEvaluateInfo($gearInfo['evaluate']); // 评测
                $gearInfo['blendent'] = $this->getBlendent($gearId);    // 配色信息
                if(!empty($gearInfo['images'])){
                    $gearInfo['images'] = json_decode($gearInfo['images'], true);
                    $gearInfo['images'] = array_slice($gearInfo['images'], 0, 5);
                }else{
                    $gearInfo['images'] = array();
                }
                $gearInfo['footType'] = json_decode($gearInfo['footType'], true);
                $gearInfo['footCircle'] = json_decode($gearInfo['footCircle'], true);

                if(isset($gearInfo['brand']['sorder']))
                {
                    unset($gearInfo['brand']['sorder']);
                }

                if(!isset($gearInfo['comscore']))
                {
                    $gearInfo['comscore'] = $this->gearComScore($gearId);  
                }
                
                if($gearInfo['images'] && $thumbImg)
                {
                    foreach ($gearInfo['images'] as & $v)
                    {
                        $v .= '?imageView2/1/w/750/h/750';
                    }
                }
            }

            if($isOne)
            {
                $gearInfos = $gearInfo;
            }
            else
            {
                $gearInfos[$gearId] = $gearInfo;
            }
        }

        return $gearInfos;
    }
    /**
     * 获取某条装备评论列表
     * @int gearId 装备id
     * @string type 评论类型 all hot
     * @int point  界限点：一个评论ID
     * @int direc  数据加载方式  next prev
     * @int offset  要获取的评论数量
     * @int p  页码
     * 说明：客户端使用前5个参数
     * @return array()
    */
    public function getGearCommentList($gearId, $type = 'all', $point = 0, $direc = 'next',$offset = 10,$p = 0)
    {
        $result = array();
        empty($direc) && $direc = 'next';
        if($gearId)
        {
            empty($offset) && $offset = 10;
            $sql = "select * from r_gear_comment where gearId = {$gearId} ";
            $count_sql = "select count(commentId) from r_gear_comment where gearId = {$gearId} ";
            if($type == 'hot')
            {
               // $offset = 10;
               // $lightLimt = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
               // $sql .= " and lights >= {$lightLimt} ";
               // $count_sql .= " and lights >= {$lightLimt}";
            }
            if($p >0)
            {
                //分页
                require FILE . 'lib/page.class.php';
                $num = $this->base->db->getone($count_sql);
                $page = new Page($num, $offset);
                $pageStr = $page->show();
                $this->base->view->assign('pageStr', $pageStr);

                $start = ($p-1) * $offset;
                $sql .= ' order by commentId DESC';
                $sql .= " limit {$start}, {$offset}";
            }
            else
            {
              //  $sql .= ' and isShow = 1';
                // if(!empty($point))
                // {
                //     $sql .= " and comment_id != {$point}";
                //     $point = $this->db->getOne("select add_time from r_news_comment where news_id = {$news_id}  and comment_id = {$point}");
                // }
                if($point > 0 && $type != 'hot')
                {
                    $sql .= " and commentId ";
                    $sql .= $direc == 'prev' ? "> {$point} " : "< {$point}";
                }
                elseif($type == 'hot')
                {
                    $sql .= ' order by lights DESC';
                }
                $type != 'hot' && $sql .=" order by commentId DESC limit {$offset}";
            }
            $result = $this->db->getall($sql);
        }
        if($result)
        {
            foreach ($result as $k => & $comment) {
                $comment['content'] = $this->replaceComment($comment['content']);     
                $comment['floor'] = $this->redis->zrank(REDIS_PREFIX.'GearComFloor_'.$gearId, $comment['commentId'])+1;
                $comment['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $comment['uid'], 'nickname');
                $comment['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $comment['uid'], 'header');
            }
        }
        return $result;
    }

    /**
     * 替换评论中的@用户
     * @return
    */
    public function replaceComment($content)
    {
        $content = trim($content);
        if($this->base->vn < 1700 || ($this->base->vn < 1900 && $this->base->projectId == 1))
        {
            preg_match_all('/(<at href="joggers:\/\/profile\/\d+">.*<\/at>)/U', $content, $matches);
            if(!empty($matches[1]))
            {
                foreach ($matches[1] as $str) {
                    $content = preg_replace('/<at href="joggers:\/\/profile\/\d+">(.*)<\/at>/U', '@${1} ', $content);
                }
            }
        }
        return $content;
    }

    /**
     * 评测详情
     * @return array
    */
    public function getEvaluateInfo($evaluate)
    {
        $result = array();
        
        $evaluate = explode('|', $evaluate);
        if(is_array($evaluate) && !empty($evaluate))
        {
            $this->base->load('bbs');
            foreach ($evaluate as $v)
            {
                $info = $_ENV['bbs']->getPostInfo($v);
                if(!empty($info))
                {
                    $result[] = array('id' => $v, 'title' => $info['title'], 'img' => array_slice($info['thumb_img'], 0, 3));
                }
            }
        }

        return $result;
    }
    /**
     * 装备配色
     * @return array
    */
    public function getBlendent($gearId)
    {
        $evaluate = intval($gearId);

        $result = $this->db->getAll("select id, color, img from r_gear_blendent where gearId =  '{$gearId}' and is_delete = 0 order by addtime ASC");

        foreach ($result as & $v)
        {
            $v['color'] = explode('|', $v['color']);
        }

        return $result;
    }

    /**
     * 品牌列表
     * @var array
    */
    public function getBrandList()
    {
        $result = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'BrandList', '-inf', '+inf');
        if(empty($result))
        {
            $result = $this->db->getAll("select brandId, sorder from r_gear_brand where isShow = 1 order by sorder ASC");
            if(!empty($result))
            {
                foreach ($result as $v) {
                    $this->redis->ZADD(REDIS_PREFIX.'BrandList', $v['sorder'], $v['brandId']);
                }
            }
        }
        if(!empty($result))
        {
            foreach ($result as & $brand) {
                $brandId = is_array($brand) ? $brand['brandId'] : $brand;
                $brand = $this->getBrandInfo($brandId);
            }
        }

        empty($result) && $result = array();
        return $result;
    }
    /**
     * 品牌信息
     * @var array
    */
    public function getBrandInfo($brandId)
    {
        $result = $this->redis->hgetAll(REDIS_PREFIX.'BrandInfo_'.$brandId);
        if(empty($result))
        {
            $result = $this->db->getRow("select * from r_gear_brand where brandId = '{$brandId}'");
            if(!empty($result))
            {
                $this->redis->hmset(REDIS_PREFIX.'BrandInfo_'.$brandId, $result);
            }
        }

        empty($result) && $result = array();
        return $result;
    }
    /**
     * 获取品牌下跑鞋列表
     * @var array
    */
    public function gearListByBrand($brandId, $gearId=0, $offset='20', $sort='publishTime', $order='DESC')
    {
        $result = array();
        $sort = strtolower($sort);

        $brandInfo = $this->getBrandInfo($brandId);
        if(empty($brandInfo) || $brandInfo['isShow'] != 1)
        {
            return $result;
        }

        $redisKey = REDIS_PREFIX.'Brand_'.$brandId.'_'.substr($sort, 0, 3); // 品牌+排序
        if(!$this->redis->EXISTS($redisKey))
        {
            $brandKey = REDIS_PREFIX.'BrandGList_'.$brandId;
            $sortKey = REDIS_PREFIX.'GearsBy_'.substr($sort, 0, 3); // 装备排序
            $this->redis->ZINTERSTORE($redisKey, array($brandKey, $sortKey), array(0, 1));
            $this->redis->EXPIRE($redisKey, 1800);
        }
        $point = 0;
        if($gearId > 0)
        {
            $point = $order == 'DESC' ? $this->redis->ZREVRANK($redisKey, $gearId) : $this->redis->ZRANK($redisKey, $gearId);
            !empty($point) && $point += 1;
        }
        $limit = array(intval($point), intval($offset));
        if($order == 'DESC')
        {
            $gearIds = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => $limit));
        }
        else
        {
            $gearIds = $this->redis->ZRANGEBYSCORE($redisKey, '-inf', '+inf', array('limit' => $limit));
        }
        if(!empty($gearIds))
        {
            foreach ($gearIds as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'])
                {
                    $result[] = array('gearId' => $gearId,
                                      'name'   => $gearInfo['name'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'likes'  => $gearInfo['likes'],
                                      'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                        );
                }
            }
        }
        empty($result) && $result = array();
        return $result;
    }
    /**
     * 推荐装备列表
     * @var array
    */
    public function gearListByRec($tid, $gearId=0, $offset='20', $sort='publishTime', $order='DESC')
    {
        $result = array();
        $sort = strtolower($sort);
        $redisKey = REDIS_PREFIX.'GearSet_'.$tid.'_'.substr($sort, 0,3); // 推荐装备+排序

        if(!$this->redis->EXISTS($redisKey))
        {
            $recKey = REDIS_PREFIX.'GearSet_'.$tid;
            $sortKey = REDIS_PREFIX.'GearsBy_'.substr($sort, 0,3); // 装备排序
            //echo $recKey,$sortKey;
            $this->redis->ZINTERSTORE($redisKey, array($recKey, $sortKey), array(0, 1));
            $this->redis->EXPIRE($redisKey, 1800);
        }
        $point = 0;
        if($gearId > 0)
        {
            $point = $order == 'DESC' ? $this->redis->ZREVRANK($redisKey, $gearId) : $this->redis->ZRANK($redisKey, $gearId);
            !empty($point) && $point += 1;
        }
        $limit = array(intval($point), intval($offset));
        if($order == 'DESC')
        {
            $gearIds = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => $limit));
        }
        else
        {
            $gearIds = $this->redis->ZRANGEBYSCORE($redisKey, '-inf', '+inf', array('limit' => $limit));
        }
        if(!empty($gearIds))
        {
            foreach ($gearIds as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'])
                {
                    $result[] = array('gearId' => $gearId,
                                      'name'   => $gearInfo['name'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'likes'  => $gearInfo['likes'],
                                      'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                        );
                }
            }
        }
        empty($result) && $result = array();
        return $result;
    }
    
    /**
     * 根据关键词获取跑鞋列表
     * @var array
    */
    public function gearListBykeywords($keywords, $attrFilter = array(),$gearId=0, $offset='20', $sort='publishTime', $order='DESC')
    {
        $result = array();
        //$sort = strtolower($sort);
        $redisKey = $this->getOrgGearListBykw($keywords, $attrFilter,$sort);
        $point = 0;
        if($gearId > 0)
        {
            $point = $order == 'DESC' ? $this->redis->ZREVRANK($redisKey, $gearId) : $this->redis->ZRANK($redisKey, $gearId);
            !empty($point) && $point += 1;
        }
        $limit = array(intval($point), intval($offset));
        if($order == 'DESC')
        {
            $gearIds = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => $limit));
        }
        else
        {
            $gearIds = $this->redis->ZRANGEBYSCORE($redisKey, '-inf', '+inf', array('limit' => $limit));
        }
        if(!empty($gearIds))
        {
            foreach ($gearIds as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'])
                {
                    $result[] = array('gearId' => $gearId,
                                      'name'   => $gearInfo['name'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'likes'  => $gearInfo['likes'],
                                      'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                        );
                }
            }
        }
        empty($result) && $result = array();
        return $result;
    }
    /**
     * 根据关键词获取装备列表
     * @var array
    */
    public function getOrgGearListBykw($keywords, $attrFilter, $sort)
    {
        extract($attrFilter);
        $gender = isset($gender) ? intval($gender) : 0;
        $feature = isset($feature) ? intval($feature) : 0;
        $shoeCat = isset($shoeCat) ? intval($shoeCat) : 0;
        $minPrice = $minPrice ? intval($minPrice) : null;
        $maxPrice = $maxPrice ? intval($maxPrice) : null;
        $brand = isset($brand) ? intval($brand) : 0;
        $score = isset($score) ? intval($score) : 0;
        $publishTime = isset($publishTime) ? strtotime($publishTime) : 0;

        $searchKey = REDIS_PREFIX.'KW_'.urlencode($keywords).'_'.$gender.'_'.$feature.'_'.$shoeCat.'_'.$minPrice.'_'.$maxPrice.'_'.$brand . '_' . $score . '_' . $publishTime;
        $relKey = $searchKey.'_'.substr($sort, 0,3); // 关键词+排序

        if(!$this->redis->EXISTS($relKey))
        {
            $sortKey = REDIS_PREFIX.'GearsBy_'.substr($sort,0,3); // 装备排序
            if(!$this->redis->EXISTS($searchKey))
            {
                /*
                $sql = 'select g.gearId from r_gear as g left join r_gear_brand as b on b.brandId = g.brand where g.isShow = 1 and b.isShow = 1 ';
                if($keywords)
                {
                    $keywords = addslashes($keywords);
                    $sql .= ' and g.`name` like "%'.$keywords.'%" ';
                }
                $gender > 0 && $sql.= "and g.gender = '{$gender}' ";
                $feature > 0 && $sql.= "and g.feature = '{$feature}' ";
                $shoeCat > 0 && $sql.= "and g.shoeCat = '{$shoeCat}' ";
                $brand > 0 && $sql.= "and g.brand = '{$brand}' ";
                $minPrice > 0 && $sql .= " and g.cnyPrice >= '{$minPrice}'";
                $maxPrice > 0 && $sql .= " and g.cnyPrice <= '{$maxPrice}'";
                $score > 0 && $sql .= " and g.score='{$score}'";
                $publishTime > 0 && $sql .= " and g.publishTime='{$publishTime}'";

                $rel = $this->db->getCol($sql);
                */
                $searcher = $this->base->load('xunSearch')->init('gear')->getSearcher();
                $xsql = "isShow:1 brandIsShow:1";
                $gender > 0 && $xsql .= " gender:$gender";
                $feature > 0 && $xsql .= " feature:$feature";
                $shoeCat > 0 && $xsql .= " shoeCat:$shoeCat";
                $brand > 0 && $xsql .= " brand:$brand";
                $score > 0 && $xsql .= " score:$score";
                $publishTime > 0 && $xsql .= " publishTime:$publishTime";
                
                $searcher->setQuery($xsql." $keywords")->setSort($sort,true)->setLimit(100);
                if($minPrice || $maxPrice){
                    $searcher->addRange('price',$minPrice,$maxPrice);
                }
                $rel = $searcher->search();
                if($rel)
                {
                    foreach ($rel as $v) {
                        $this->redis->ZADD($searchKey, 1, $v->gearId);
                    }
                    $this->redis->EXPIRE($searchKey, 1800);
                }
            }
            $this->redis->ZINTERSTORE($relKey, array($searchKey, $sortKey), array(0, 1));
            $this->redis->EXPIRE($relKey, 1800);
        }
        return $relKey;
    }
    
    /**
     * 通过选鞋工具获取跑鞋列表
     * @var array
    */
    public function getOneShoeUseSt($height,$weight, $runPlace,$footCircle, $footType, $isHealth,$attrFilter, $sort='publishTime', $order='DESC'){
        $compositeAttr = $this->getCompShoeAttr($height,$weight, $runPlace,$footCircle, $footType, $isHealth);
        $sort = strtolower($sort);
        
        $result = false;
        extract($attrFilter);
        $gender = isset($gender) ? intval($gender) : 0;
        $feature = isset($feature) ? intval($feature) : 0;
        $minPrice = isset($minPrice) ? intval($minPrice) : 0;
        $maxPrice = isset($maxPrice) ? intval($maxPrice) : 0;
        $brand = isset($brand) ? intval($brand) : 0;
        $level = isset($level) ? intval($level) : 0;

        $runPlace = intval($runPlace);
        $compositeAttr = intval($compositeAttr);
        $searchKey = REDIS_PREFIX.'OneSt_'.$gender.'_'.$runPlace.'_'.$compositeAttr.'_'.$feature.'_'.$minPrice.'_'.$maxPrice.'_'.$brand.'_'.$level.'_'.$sort.'_'.$order;
        
        if(!$this->redis->EXISTS($searchKey))
        {
            $sql = "select g.gearId from r_gear as g left join r_gear_brand as b on g.brand = b.brandId where g.isShow = 1 and b.isShow =1 and g.shoeCat ";
            if($runPlace == 1)
            {
                $sql .= ' = 4';
            }
            else
            {
                $sql .= ' < 4';
                $sql .= $this->getExtSql($compositeAttr);
            }
            $gender > 0 && $sql.= " and g.gender = '{$gender}'";
            $feature > 0 && $sql.= " and g.feature = '{$feature}'";
            $brand > 0 && $sql.= " and g.brand = '{$brand}'";
            $minPrice > 0 && $sql .= " and g.cnyPrice >= '{$minPrice}'";
            $maxPrice > 0 && $sql .= " and g.cnyPrice <= '{$maxPrice}'";
            $level > 0 && $sql .= " and g.level = {$level}";
            $sql .= " order by $sort $order";
            $gearId = $this->db->getOne($sql);
            if($gearId){
                $this->redis->set($searchKey,$gearId);
                $this->redis->expire($searchKey, 1800);
            }
        }else{
            $gearId = $this->redis->get($searchKey);
        }
        
        $gearInfo = $this->getGearInfo($gearId);
        if($gearInfo && $gearInfo['isShow'])
        {
            $result = array('gearId' => $gearId,
                              'name'   => $gearInfo['name'],
                              'price'  => $gearInfo['price'],
                              'currency'  => $gearInfo['currency'],
                              'likes'  => $gearInfo['likes'],
                              'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                              'possess' => $gearInfo['possess'],
                              'level' => common::$shoeAttr['level'][$gearInfo['level']],
                              'funcTag' => common::$shoeAttr['funcTag'][$gearInfo['funcTag']],
                );
        }
        return $result;
    }
    
    /**
     * 通过选鞋工具获取跑鞋列表
     * @var array
    */
    public function getShoeUseSt($height,$weight, $runPlace,$footCircle, $footType, $isHealth,$attrFilter, $gearId, $offset, $sort, $order)
    {
        $result = array();
        $compositeAttr = $this->getCompShoeAttr($height,$weight, $runPlace,$footCircle, $footType, $isHealth);
        $sort = strtolower($sort);
        $redisKey = $this->getGearListBySt($attrFilter, $runPlace, $compositeAttr, $sort);
        $point = 0;
        if($gearId > 0)
        {
            $point = $order == 'DESC' ? $this->redis->ZREVRANK($redisKey, $gearId) : $this->redis->ZRANK($redisKey, $gearId);
            !empty($point) && $point += 1;
        }
        $limit = array(intval($point), intval($offset));
        if($order == 'DESC')
        {
            $gearIds = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => $limit));
        }
        else
        {
            $gearIds = $this->redis->ZRANGEBYSCORE($redisKey, '-inf', '+inf', array('limit' => $limit));
        }
        if(!empty($gearIds))
        {
            foreach ($gearIds as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'])
                {
                    $result[] = array('gearId' => $gearId,
                                      'name'   => $gearInfo['name'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'likes'  => $gearInfo['likes'],
                                      'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                        );
                }
            }
        }
        empty($result) && $result = array();
        return $result;
    }
    /**
     * 选鞋工具 装备列表
     * @var array
    */
    public function getGearListBySt($attrFilter, $runPlace, $compositeAttr, $sort)
    {
        $result = false;
        extract($attrFilter);
        $gender = isset($gender) ? intval($gender) : 0;
        $feature = isset($feature) ? intval($feature) : 0;
        $minPrice = isset($minPrice) ? intval($minPrice) : 0;
        $maxPrice = isset($maxPrice) ? intval($maxPrice) : 0;
        $brand = isset($brand) ? intval($brand) : 0;

        $runPlace = intval($runPlace);
        $compositeAttr = intval($compositeAttr);
        $searchKey = REDIS_PREFIX.'St_'.$gender.'_'.$runPlace.'_'.$compositeAttr.'_'.$feature.'_'.$minPrice.'_'.$maxPrice.'_'.$brand; // 综合+排序
        $relKey = $searchKey.'_'.substr($sort, 0,3); // 综合+排序
        if(!$this->redis->EXISTS($relKey))
        {
            $sortKey = REDIS_PREFIX.'GearsBy_'.substr($sort, 0,3); // 装备排序
            if(!$this->redis->EXISTS($searchKey))
            {
                $sql = "select g.gearId from r_gear as g left join r_gear_brand as b on g.brand = b.brandId where g.isShow = 1 and b.isShow =1 and g.shoeCat ";
                if($runPlace == 1)
                {
                    $sql .= ' = 4';
                }
                else
                {
                    $sql .= ' < 4';
                    $sql .= $this->getExtSql($compositeAttr);
                }
                $gender > 0 && $sql.= " and g.gender = '{$gender}'";
                $feature > 0 && $sql.= " and g.feature = '{$feature}'";
                $brand > 0 && $sql.= " and g.brand = '{$brand}'";
                $minPrice > 0 && $sql .= " and g.cnyPrice >= '{$minPrice}'";
                $maxPrice > 0 && $sql .= " and g.cnyPrice <= '{$maxPrice}'";
                $rel = $this->db->getCol($sql);
                if($rel)
                {
                    foreach ($rel as $v) {
                        $this->redis->ZADD($searchKey, 1, $v);
                    }
                    $this->redis->EXPIRE($searchKey, 1800);
                }
            }
            $this->redis->ZINTERSTORE($relKey, array($searchKey, $sortKey), array(0, 1));
            $this->redis->EXPIRE($relKey, 1800);
        }
        return $relKey;
    }
    /**
     * 根据身高、体重、跑步场地、适合足类、足型、是否伤病获取综合参数
     * @var array
    */
    public function getCompShoeAttr($height,$weight, $runPlace,$footCircle, $footType, $isHurt)
    {
        $footCircle = $this->getReviseFootType($footCircle, $footType);
        $normalBMI = $this->isNormalBMI($height, $weight);

        $footCircle = $footCircle == 1 ? 10 : ($footCircle == 2 ? 30 : 20);
        $normalBMI = $normalBMI ? 1 : 2;
        $isHurt = $isHurt ? 2 : 0;
        $parameter = $footCircle + $normalBMI + $isHurt;
        $parameter = $runPlace == 1 ? 0 : $parameter;
        return $parameter;
    }
    /**
     * 根据身高体重信息计算BMI是否正常
     * int $height   (cm)
     * float $weight   (kg)
     * @var boolen
    */
    public function isNormalBMI($height, $weight)
    {
        $result = false;
        if($height * $weight > 0)
        {
            $result = $weight*10000/($height*$height) < 24;
        }
        return $result;
    }
    /**
     * 根据足型与适合足类选择值的结果组合，获取适合足类的修正结果
     * int $footType  足型
     * int $footCircle   适合足类
     * @var int
    */
    public function getReviseFootType($footCircle, $footType)
    {
        $result = 1;
        switch ($footCircle) {
            case '1':
                $result = 1;
                break;
            case '2':
                $result = $footType == 3 ? 1 : 2;
                break;
            case '3':
                $result = $footType == 1 ? 1 : 3;
                break;
            default:
                $result = $footType == 1 ? 2 :($footType == 3 ? 3 : 1);
                break;
        }
        return $result;
    }
    /**
     * 适合足类与是否有受伤、BMI三个条件组合的结果
     * int $footCircle   适合足类
     * boolen $normalBMI   BMI是否正常， true为正常
     * boolen $healthy   是否健康， true为健康
     * @var array
    */
    public function getExtSql($parameter)
    {
        $sql = ' and ';
        $parameter = intval($parameter);
        if($parameter == 11)
        {
            $sql .= '(funcTag = 1 or (funcTag = 4 and level = 2))';
        }
        else if($parameter == 12)
        {
            $sql .= '((funcTag = 1 and level != 3) or (funcTag = 4 and level = 2))';
        }
        else if($parameter == 13)
        {
            $sql .= '((funcTag = 1 and level = 1) or (funcTag = 4 and level != 3))';
        }
        else if($parameter == 14)
        {
            $sql .= '((funcTag = 1 and level = 1) or (funcTag = 4 and level = 1))';
        }
        else if($parameter == 21)
        {
            $sql .= '(funcTag = 2)';
        }
        else if($parameter == 22)
        {
            $sql .= '((funcTag = 2 and level = 1) or (funcTag = 3 and level != 3))';
        }
        else if($parameter == 23)
        {
            $sql .= '((funcTag = 3 and level = 2) or (funcTag != 1 and level = 1))';
        }
        else if($parameter == 24)
        {
            $sql .= '(funcTag != 1 and level = 1)';
        }
        else if($parameter == 31)
        {
            $sql .= '(funcTag = 1)';
        }
        else if($parameter == 32)
        {
            $sql .= '((funcTag = 1 and level != 3) or (funcTag = 4 and level = 2))';
        }
        else if($parameter == 33)
        {
            $sql .= '((funcTag = 1 and level = 1) or (funcTag = 4 and level != 3))';
        }
        else
        {
            $sql .= '((funcTag = 1 and level = 1) or (funcTag = 4 and level = 1))';
        }
        return $sql;
    }
    /**
     * 热门搜索词
     * @var array
    */
    public function getHotKeywords($limit = 10)
    {
        $limit = intval($limit);
        $result = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GearKw', '+inf', '-inf', array('limit' => array(0, $limit)));
        if(!empty($result))
        {
            foreach ($result as & $v) {
                $v = base64_decode($v);
            }
        }
        else
            $result = array();
        return $result;
    }

    /**
     * 主页推荐 2.5.0+
     * @var array
    */
    public function homeRecGear()
    {
        $result = $this->redis->get(REDIS_PREFIX.'GearHomeBest');
        if($result)
        {
            $result = json_decode($result, true);
        }
        !$result && $result = array();
        return $result;
    }

    /**
     * 猜你喜欢
     * @var array
    */
    public function mayLike($uid, $limit = 10)
    {
        $gears = array();
        $skimGears = $this->getLatestSkim($uid);
        if(!empty($skimGears))
        {
            $attrs = $this->db->getAll('select shoeCat, feature from r_gear where gearId '.$this->base->load('push')->db_create_in($skimGears));
            $tmpGears = $this->db->getCol('select distinct(g.gearId) from r_gear as g left join r_gear_brand as b on b.brandId = g.brand where b.isShow = 1 and g.isShow = 1 and g.shoeCat '.$this->base->load('push')->db_create_in(array_unique($attrs['shoeCat'])).' and g.feature '.$this->base->load('push')->db_create_in(array_unique($attrs['feature'])).' order by g.likes DESC limit 20');
            if(!empty($tmpGears))
            {
                foreach (array_rand($tmpGears, $limit) as $v) {
                    $gears[] = $tmpGears[$v];
                }
            }
        }
        if(empty($gears))
        {
            $gears = $this->latestLike($limit);
        }
        if(!empty($gears))
        {
            foreach ($gears as & $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo)
                {
                    $gearId = array('gearId' => $gearInfo['gearId'],
                                    'name' => $gearInfo['name'],
                                    'price' => $gearInfo['price'],
                                    'currency' => $gearInfo['currency'],
                                    'likes' => $gearInfo['likes'],
                                    'image' => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                        );
                }
            }
        }
        return $gears;
    }
    /**
     * 用户最近浏览的产品
     * @var array
    */
    public function getLatestSkim($uid, $limit = 5)
    {
        $limit = intval($limit);
        $gears = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'LatestSkim_'.$uid, '+inf', '-inf', array('limit' => array(0, $limit)));
        return $gears;
    }
    /**
     * 用户最近喜欢的产品
     * @var array
    */
    public function latestLike($limit = 10, $totalNum = 20)
    {
        $redisKey = REDIS_PREFIX.'GearLatestLike';
        if(!$this->redis->EXISTS($redisKey))
        {
            $data = $this->db->getCol("select distinct(gearId) from r_gear_likes where isShow = 1 order by addTime DESC limit $totalNum");
             $list = array();
            if($data)
            {

                $i = 0;
                foreach ($data as $v) {
                    $gearInfo = $this->getGearInfo($v);
                    if($gearInfo && $gearInfo['isShow'] == 1)
                    {
                        if($i < $limit)
                        {
                            $i += 1;
                            $list[] = $v;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            if($list)
            {
                $this->redis->set($redisKey, json_encode($list));
                $this->redis->EXPIRE($redisKey, 3600);
                return $data;
            }
        }
        $gears = $this->redis->get($redisKey);
        if($gears)
        {
            $gears = json_decode($gears, true);
        }
        else
            $gears = array();
        return $gears;
    }
    /**
     * 搜索结果为空时的装备推荐
     * @var array
    */
    public function searchRecList($limit = 10)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'SearcjRecGear';
        if(!$this->redis->EXISTS($redisKey))
        {
            $gears = $this->db->getCol("select distinct(g.gearId) from r_gear as g left join r_gear_brand as b on g.brand = b.brandId where b.isShow = 1 and g.isShow = 1 order by g.publishTime DESC,g.likes DESC limit $limit");
        }
        else
        {
            $gears = $this->redis->get($redisKey);
            if($gears)
                $gears = json_decode($gears, true);
        }
        if($gears)
        {
            foreach ($gears as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'] == 1)
                {
                    $result[] = array('gearId' => $gearId,
                                      'name'   => $gearInfo['name'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'likes'  => $gearInfo['likes'],
                                      'image'  => empty($gearInfo['images']) ? '' : $gearInfo['images'][0]
                            );
                }
            }
        }
        return $result;
    }
    /**
     * 喜欢装备
     * @param gearId 装备id
     * @param uid  用户ID
     */
    public function likeGear($gearId, $uid)
    {
        $result = false;
        $gearInfo = $this->getGearInfo($gearId);
        if(empty($gearInfo) || $gearInfo['isShow'] != 1)
        {
            return $result;
        }
        //if($this->redis->ZSCORE(REDIS_PREFIX.'GearLikeList_'.$gearId, $uid) === false)
        if($this->db->getRow("select * from r_gear_likes where gearId={$gearId} and uid={$uid}")){
            return $result;
        }else{
            $addTime = $this->base->time;
            $isShow = 1;
            $likeArray = compact('gearId','uid','addTime','isShow');
            $rid = $this->db->insertRowTable('r_gear_likes', $likeArray);
            if($rid)
            {
                // $this->redis->ZADD(REDIS_PREFIX.'GearLatestLike', $rid, $gearId);
                $this->redis->zadd(REDIS_PREFIX.'GearLikeList_'.$gearId, $addTime, $uid);
                if($this->db->update("update r_gear set likes = likes+1 where gearId = '{$gearId}'"))
                {
                    $this->redis->HINCRBY(REDIS_PREFIX. 'GearInfo_'.$gearId, 'likes', 1);
                    $this->redis->ZINCRBY(REDIS_PREFIX.'GearsBy_lik', 1, $gearId);
                }
                $result = $this->db->getOne("select likes from r_gear where gearId = {$gearId}");
            }
        }
        return $result;
    }
    /**
     * 取消喜欢装备
     * @param gearId 装备id
     * @param uid  用户ID
     */
    public function unlikeGear($gearId, $uid)
    {
        $result = false;
        $gearInfo = $this->getGearInfo($gearId);
        if(empty($gearInfo) || $gearInfo['isShow'] != 1)
        {
            return $result;
        }
        if($this->redis->ZSCORE(REDIS_PREFIX.'GearLikeList_'.$gearId, $uid) != false)
        {
            $isShow = 1;
            $likeArray = compact('gearId','uid','isShow');
            if($this->db->updateRowTable('r_gear_likes', $likeArray))
            {
                $this->redis->ZREM(REDIS_PREFIX.'GearLikeList_'.$gearId, $uid);
                if($this->db->update("update r_gear set likes = likes-1 where gearId = '{$gearId}'"))
                {
                    $this->redis->HINCRBY(REDIS_PREFIX. 'GearInfo_'.$gearId, 'likes', -1);
                    $this->redis->ZINCRBY(REDIS_PREFIX.'GearsBy_lik', -1, $gearId);
                }
                $result = true;
            }
        }
        return $result;
    }

    /**
     * 增加浏览量
     * @param $gearId 装备id
     * @return mixed
     */
    public function incrViewCounts($gearId)
    {
        $result=$this->db->update("update r_gear set viewCounts = viewCounts + 1 where gearId = '{$gearId}'");

        return $result;
    }
    /**
     * 装备总喜欢数
     * @param gearId 装备id
     * @return int
     */
    public function getTotalLike($gearId)
    {
        $likes = $this->redis->ZCARD(REDIS_PREFIX.'GearLikeList_'.$gearId);
        return intval($likes);
    }
    /**
     * 发布评论
     * @param gearId 装备id
     * @param content 评论内容
     * @param fatherId 父级评论id
     * @return int  commentId  生成的评论id
     */
    public function comment($gearId, $content, $score, $uid, $fatherId=0, $imgField = 'image')
    {
        $result = false;
        $addTime = $this->base->time;
        $this->redis->set(REDIS_PREFIX.'GearComment'.$uid, $addTime, 30);
        $gearInfo = $this->getGearInfo($gearId);
        if(!empty($gearInfo) && $gearInfo['isShow'] == 1 && $uid)
        {
            if($score)
            {
                $isScore = $this->db->getOne("select count(1) from r_gear_comment where uid='{$uid}' and gearId='{$gearId}' and score>0");

                if($isScore)
                {
                    $_ENV['error']->getErrors(601);
                    exit;
                }
            }

            if(!empty($fatherId))
            {
                $fatherId = $this->db->getone("select uid from r_gear_comment where gearId = {$gearId} and commentId = {$fatherId} limit 1");
                if(empty($fatherId))
                {
                    $_ENV['error']->getErrors(101);
                    exit();
                }
            }

            $images = $thumbImgs = $thumbSizes = array();
            !is_array($imgField) && $imgField[] = $imgField;
            $imgFields = $imgField;

            foreach($imgFields as $imgField)
            {            
                $image = $this->base->load('qiniu')->uploadQiNiuImg($imgField, md5($gearId.'/'.$addTime.common::getHashStr(6)));
                $img_size = empty($image) ? array() : getimagesize($_FILES[$imgField]['tmp_name']);
                if(!empty($img_size) && !empty($image))
                {
                    $thumbInfo = $this->base->load('news')->getThumbInfo($img_size[0], $img_size[1]);
                    extract($thumbInfo);
                    $thumbImg = empty($thumb_img) ? $image : $image .'?imageMogr2/thumbnail/220x220';
                    $thumbSize = $thumb_size;
                }
                else
                {
                    $thumbSize = '0x0';
                    $thumbImg = '';
                }

                $images[] = $image;
                $thumbImgs[] = $thumbImg;
                $thumbSizes[] = $thumbSize;
            }

            $image = json_encode($images);
            $thumbImg = json_encode($thumbImgs);
            $thumbSize = json_encode($thumbSizes);

            $comment = compact('gearId','fatherId','uid','content','addTime', 'image','thumbImg','thumbSize','score');
            $commentId = $this->db->insertRowTable('r_gear_comment', $comment);
            if($commentId)
            {
                // 评论楼层
                $this->redis->zadd(REDIS_PREFIX.'GearComFloor_'.$gearId, $commentId, $commentId);
                $floor = $this->redis->zrank(REDIS_PREFIX.'GearComFloor_'.$gearId, $commentId)+1;
                $this->base->result['result'] = compact('commentId' ,'floor','image', 'thumbImg','content', 'thumbSize', 'score');
                $this->base->breakCall();
                $this->redis->HINCRBY(REDIS_PREFIX. 'GearInfo_'.$gearId, 'comments', 1);
                $this->db->update("update r_gear set comments = comments+1 where gearId = '{$gearId}'");

                if($score)
                {
                    $this->db->update("update r_gear set possess = possess+1 where gearId = '{$gearId}'");
                }
            }
            else
            {
                $_ENV['error']->getErrors(100);
                exit;
            }
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 获取装备的评论列表
     * @return array()
     */
    public function getCommentList($gearId, $point = 0, $direc = 'next',$offset = 10,$p = 0)
    {
        $result = array();
        $gearId = intval($gearId);
        if($gearId <= 0)
        {
            return NULL;
        }
        $sql = "select * from r_gear_comment where gearId = {$gearId} ";
        if($p >0)
        {
            //分页
            require FILE . 'lib/page.class.php';
            $count_sql = "select count(commentId) from r_gear_comment where gearId = {$gearId} ";
            $num = $this->db->getone($count_sql);
            $offset = empty($offset) ? 10 : $offset;
            $page = new Page($num, $offset);
            $pageStr = $page->show();

            $this->base->view->assign('pageStr', $pageStr);

            $start = ($p-1) * $offset;
            $sql .= " order by addTime DESC limit {$start}, {$offset}";
        }
        else
        {
            $sql .= ' and isShow = 1';
            if($point > 0)
            {
                $sql .= " and commentId ";
                $sql .= $direc == 'prev' ? "> {$point} order by addTime ASC" : "< {$point} ORDER BY addTime DESC";
            }
            else
            {
                $sql .= ' ORDER BY addTime DESC';
            }
            $sql .=" limit {$offset}";
        }
        $result = $this->db->getall($sql);
        if($result)
        {
            $point > 0 && $direc == 'prev' && rsort($result);
            $user = $this->base->uid;
            foreach ($result as $k => & $v) {
                $v['floor'] = $this->redis->zrank(REDIS_PREFIX.'GearComFloor_'.$gearId, $v['commentId'])+1;
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $v['uid'], 'nickname');
                $v['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $v['uid'], 'header');
                $v['is_lighten'] = $this->redis->hexists(REDIS_PREFIX.'GearComLight'.$v['commentId'], $user) ? 1 : 0;
            }
        }
        return $result;
    }
    /**
     * 点亮某装备评论
     * @int commentId 评论id
     * @return int  is_success 是否成功
     */
    public function upComment($uid, $commentId = 0)
    {
        $comInfo = $this->db->getRow("select commentId, gearId, uid, lights from r_gear_comment where commentId = {$commentId} and isShow =1");
        if(!empty($comInfo))
        {
            //检查用户是否已点亮过该评论
            if($this->redis->hexists(REDIS_PREFIX.'GearComLight'.$commentId, $uid))
            {
                $_ENV['error']->getErrors(405);
                exit();
            }
            $addTime = $this->base->time;
            $insertArray = compact('addTime', 'uid', 'commentId');
            $is_success = $this->db->insertRowTable('r_gearcom_like', $insertArray) ? 1 : 0;
            if($is_success)
            {
                $this->db->query("update r_gear_comment set lights = lights +1 where commentId = {$commentId}");
                $this->redis->hset(REDIS_PREFIX.'GearComLight'.$commentId, $uid, $this->base->time);
                $this->redis->HINCRBY(REDIS_PREFIX.'GearInfo_'.$comInfo['gearId'], 'lights', 1);
                $comInfo['lights'] +1 >= $this->base->config['NEWS_HOT_COMMENT_LIMIT'] && $this->updateHotComments($comInfo['gearId']);
            }
            return $is_success;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /*
     * 获取某装备的热门评论
     * @return $array
    */
    public function hotComments($gearId)
    {
        $result = $this->redis->get(REDIS_PREFIX .'GearHotComs'.$gearId);
        if(common::is_json($result))
        {
            $uid = $this->base->uid;
            $result = json_decode($result, true);
            foreach ($result as & $v) {
                $v['is_lighten'] = $this->redis->hexists(REDIS_PREFIX.'Gearlight_'.$v['commentId'], $uid) ? 1 : 0;
            }
        }
        empty($result) && $result = array();
        return $result;
    }
    /**
     * 更新某装备的热门评论
     * @int gearId 装备id
     * @return
     */
    public function updateHotComments($gearId, $limit = 20)
    {
        $upLimit = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
        $result = $this->db->getAll("select * from r_gear_comment where isShow = 1 and gearId = '{$gearId}' and lights >= '{$upLimit}' order by lights DESC limit $limit");
        if($result)
        {
            foreach ($result as $key => & $v) {
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'nickname');
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'header');
                $v['floor'] = $this->redis->zrank(REDIS_PREFIX.'GearComFloor_'.$gearId, $v['commentId'])+1;
            }
        }
        $this->redis->set(REDIS_PREFIX .'GearHotComs'.$gearId, json_encode($result));
        return $result;
    }
    /**
     * 隐藏评论
     * @int commentId 评论id
     * @return int  is_success 是否成功
     */
    public function hideComment($uid, $commentId)
    {
        $result = 0;
        $commentInfo = $this->db->getRow("select gearId, lights, isShow from r_gear_comment where uid = '{$uid}' and commentId = '{$commentId}' limit 1");
        if(!empty($commentInfo) && $commentInfo['isShow'] == 1)
        {
            if($this->db->update("update r_gear_comment set isShow = 0 where commentId = '{$commentId}'"))
            {
                $this->base->result['result']['is_success'] = 1;
                $this->base->breakCall();
                $gearId = $commentInfo['gearId'];
                $commentInfo['lights']-1 > $this->base->config['NEWS_HOT_COMMENT_LIMIT'] && $this->updateHotComments($gearId);
                $this->redis->HINCRBY(REDIS_PREFIX. 'GearInfo_'.$gearId, 'comments', -1);
                $this->db->update("update r_news set comments = comments-1 where gearId = '{$gearId}'");
            }
        }
        return $result;
    }
    /**
     * 装备对比
     * @return array()
    */
    public function GearCompare($gears = array())
    {
        $result = array();
        if($gears)
        {
            $shoeAttr = common::$shoeAttr;
            foreach ($gears as $gearId) {
                $gearInfo = $this->getGearInfo($gearId);
                if($gearInfo && $gearInfo['isShow'] == 1)
                {
                    $tmp = array('gearId' => $gearInfo['gearId'],
                                      'name'    => $gearInfo['name'],
                                      'gender'    => $gearInfo['gender'] == 1 ? '男' : '女',
                                      'brand'    => $gearInfo['brand']['brandName'],
                                      'price'  => $gearInfo['price'],
                                      'currency'  => $gearInfo['currency'],
                                      'image'    => empty($gearInfo['images']) ? '' : $gearInfo['images'][0],
                                      'shoeCat'    => $shoeAttr['shoeCat'][$gearInfo['shoeCat']],
                                      'feature' => $shoeAttr['feature'][$gearInfo['feature']],
                                      'weight' => $gearInfo['weight'],
                                      'publishTime' => date("Y-m", $gearInfo['publishTime']),

                        );
                    foreach ($gearInfo['footType'] as $v) {
                        $tmp['footType'][] = $shoeAttr['footType'][$v];
                    }
                    $tmp['footType'] = implode(',',$tmp['footType']);
                    foreach ($gearInfo['footCircle'] as $v) {
                        $tmp['footCircle'][] = $shoeAttr['footCircle'][$v];
                    }
                    $tmp['footCircle'] = implode(',',$tmp['footCircle']);
                    $result[] = $tmp;
                }
            }
        }
        return $result;
    }
    /**
     * 同类装备推荐
     * @return array()
    */
    public function getSimilarGear($shoeCat = 1, $feature = 1, $limit = 10, $allNum = 15)
    {
        $result = array();
        $allNum = intval($allNum);
        $redisKey = REDIS_PREFIX.'SMGear_'.$shoeCat.'_'.$feature;
        $allGear = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => array(0, $allNum)));
        if(!$allGear)
        {
            $allGear = array();
            $data = $this->db->getAll("select g.gearId, g.likes,g.shortDesc from r_gear as g left join r_gear_brand as b on g.brand = b.brandId where b.isShow = 1 and g.isShow = 1 order by g.likes DESC limit {$allNum}");
            if($data)
            {
                foreach ($data as $v) {
                    $this->redis->ZADD($redisKey, $v['likes'], $v['gearId']);
                    $allGear[] = $v['gearId'];
                }
                $this->redis->EXPIRE($redisKey, 3600);
            }
        }

        if($allGear)
        {
            $limit = $limit > count($allGear) ? count($allGear) : $limit;
            $randKey = array_rand($allGear, $limit);
            if(!is_array($randKey)){
                $tmp=$randKey;
                $randKey=array();
                $randKey[]=$tmp;
            }
            $maxKey = $randKey%2 == 0 ? ($limit-1) : $limit;
            foreach ($randKey as $k => $key) {
                if($k <= $maxKey)
                {
                    $tmpGear = $allGear[$key];
                    $tmpGearInfo = $this->getGearInfo($tmpGear);
                    if($tmpGearInfo)
                    {
                        $result[] = array('gearId' => $tmpGear,
                                          'name'   => $tmpGearInfo['name'],
                                          'price'  => $tmpGearInfo['price'],
                                          'currency'  => $tmpGearInfo['currency'],
                                          'shopUrl'  => $tmpGearInfo['shopUrl'],
                                          'likes'  => $tmpGearInfo['likes'],
                                          'image'  => empty($tmpGearInfo['images']) ? '' : $tmpGearInfo['images'][0],
                                          'shortDesc' => $tmpGearInfo['shortDesc']
                            );
                    }
                    unset($tmpGear, $tmpGearInfo);
                }
            }
        }
        return $result;
    }
    /**
     * 生成装备价格排行
     * @return
    */
    public function createPriceList()
    {
        $redisKey = REDIS_PREFIX.'GearsBy_pri';
        $gears = $this->db->getAll('select g.gearId, g.cnyPrice from r_gear as g left join r_gear_brand as b on g.brand = b.brandId where b.isShow = 1 and g.isShow = 1');
        if($gears)
        {
            foreach ($gears as $key => $v) {
                $this->redis->ZADD($redisKey, $v['cnyPrice'], $v['gearId']);
            }
        }
        if($rel) print_r($rel);
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成装备喜欢排行
     * @return
    */
    public function createLikeList()
    {
        $redisKey = REDIS_PREFIX.'GearsBy_lik';
        $gears = $this->db->getAll('select g.gearId, g.likes from r_gear as g left join r_gear_brand as b on b.brandId = g.brand where b.isShow = 1 and g.isShow = 1');
        if($gears)
        {
            foreach ($gears as $key => $v) {
                $this->redis->ZADD($redisKey, $v['likes'], $v['gearId']);
            }
        }
        if($rel) print_r($rel);
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成装备发布时间排行
     * @return
    */
    public function createpubList()
    {
        $redisKey = REDIS_PREFIX.'GearsBy_pub';
        $gears = $this->db->getAll('select g.gearId, g.publishTime, g.likes from r_gear as g left join r_gear_brand as b on b.brandId = g.brand where b.isShow = 1 and g.isShow = 1');
        if($gears)
        {
            foreach ($gears as $key => $v) {
                $score = $v['publishTime'] + $v['likes'];
                $this->redis->ZADD($redisKey, $score, $v['gearId']);
            }
        }
        if($rel) print_r($rel);
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成品牌下装备列表redis数据
     * @var array
    */
    public function creteBrandGearList($brand)
    {
        $brand = intval($brand);
        $gears = $this->db->getCol("select gearId from r_gear where brand = '{$brand}' and isShow = '1'");
        if($gears)
        {
            $redisKey = REDIS_PREFIX.'BrandGList_'.$brand;
            foreach ($gears as $key => $gearId) {
                $this->redis->ZADD($redisKey, $key, $gearId);
            }
        }
        return ;
    }

      /**
     * 装备综合评分
     * @int gearId 装备id
     * @return string comscore 综合评分
     */
    public function gearComScore($gearId, $update = false)
    {
        // $gearInfo = $this->redis->hgetAll(REDIS_PREFIX.'GearInfo_'.$gearId);

        // if($gearInfo['comscore'])
        //   $comscore = $gearInfo['comscore'];

        // if($comscore || $update == false)
        // {
        //     return $comscore;
        // }
        $gearId = intval($gearId);
        $comscore = $this->db->getone("select score from r_gear where gearId = '{$gearId}'");
        $gear_comment_avg_score = $this->base->db->getOne("select avg(score) from r_gear_comment where gearId = '{$gearId}' AND isShow = 1");

        if($gear_comment_avg_score > 0)
        {
            $comscore = 0.6* $comscore + 0.4 * $gear_comment_avg_score;
        }
          

        $comscore = number_format($comscore,1);
        
         return $comscore;
    }
   
    /**
    *工具函数，街区前50个中文
    */
    private function cut50($o){
        //var_dump($o);
        $len=50;             
        if(mb_strlen($o,'utf-8')>$len){
            return mb_substr($o,0,$len-2,'utf-8')."......";
        }
        return $o;
    }
    /**
    *
    *@from /show/index
    *装备首页返回装备
    */
    public function showgearGetg($id){        
        $sql="select gearId,name,images,shortDesc,score,likes,possess from r_gear where gearId={$id} and isShow=1 ";
        $return=$this->db->getRow($sql);
        if($return){
            $return['s']=$this->cut50($return['shortDesc']);
            $tmp=json_decode($return['images'],true);
            $return['img']=$tmp?$tmp[0]:'';
            
        }            
        return $return;    
    }
    /**
    *
    *@from /show/index
    *装备首页返回集合
    */
    public function showgearGets($id){        
        $sql="select setId,setName,img,setDescribe,setDescribe from r_gear_sets where setId={$id} and isShow=1 ";
        $return=$this->db->getRow($sql);
        if($return){
            $return['s']=$this->cut50($return['setDescribe']);
            $tmp=json_decode($return['img'],true);
            $return['img']=$tmp?$tmp[0]:'';
           
            //echo $return['img'];
        }
        return $return;    
    }
    /**
    *
    *@from /show/index
    *装备首页返回评测
    */
    public function showgearGetn($id){
        $sql="select news_id,uid,title,short_desc,thumb_img,loves,total_comment,author from r_news where news_id={$id} and is_show=1 ";
        //echo $sql;return;
        if(!$return=$this->db->getRow($sql)){
            return $return;
        }
        $tmp=json_decode($return['thumb_img'],true);
        $return['img']=$tmp?$tmp[0]:'';
        //$return['img']=stripslashes($return['img']);
         //echo $return['img'];
        $return['header']=$this->db->getOne("select header from r_user where uid='".$return['uid']."'");
        if($return){
            $return['s']=$this->cut50($return['short_desc']);
        }
        return $return;    
    }

    // 获取装备合辑基本信息
    public function getSetInfo($sid)
    {
        return $this->db->getRow("select * from r_gear_sets where setId='$sid'");
    }

    // 删除用户想要、拥有的装备
    public function delUserGear($uid, $type, $gearId)
    {
        $result = FALSE;

        if(!$type)
        {
            $result = $this->redis->srem(REDIS_PREFIX.'gear_likes_'.$gearId, $uid);
            $result && $this->db->query("delete from r_gear_likes where uid='{$uid}' and gearId='{$gearId}'");
            $result && $this->db->query("update r_gear set likes=likes-1 where gearId='{$gearId}' and likes>0"); 
        }
        else
        {
            $result = $this->db->query("delete from r_gear_comment where gearId='{$gearId}' and uid='{$uid}' and score>0");
            $result && $this->db->query("update r_gear set possess=possess-1 where gearId='{$gearId}' and possess>0");
        }

        return $result;
    }

    // 获取用户想要、拥有的装备
    public function getUserGearList($uid, $type, $page, $num = 10)
    {
        $result = array();

        if(!$type)
        {
            $count = $this->db->getOne("select count(1) from r_gear_likes where uid='{$uid}'");
            $pages = ceil($count / $num);
            $page < 1 && $page = 1;
            $begin = ($page - 1) * $num;

            if($count)
            {
                $result = $this->db->getAll("select b.* from r_gear_likes a left join r_gear b on a.gearId=b.gearId where a.uid='{$uid}' order by rid desc limit {$begin},{$num}");
            }
        }
        else
        {
            $count = $this->db->getOne("select count(1) from r_gear_comment where uid='{$uid}' and score>0");
            $pages = ceil($count / $num);
            $page < 1 && $page = 1;
            $begin = ($page - 1) * $num;

            if($count)
            {
                $result = $this->db->getAll("select b.*,a.mileage from r_gear_comment a right join r_gear b on a.gearId=b.gearId where a.uid='{$uid}' and a.score>0 order by commentId desc limit {$begin},{$num}");
            }
        }

        if($result)
        {
            foreach ($result as $key => $value)
            {
                //$result[$key]['scheme'] = 'joggers://gearShoe/' . $value['gearId'];
                $result[$key]['scheme'] = 'http://'.$this->base->config['host'].'/show/equipment?gearId=' . $value['gearId'];
                $result[$key]['images'] = !empty($value['images']) ? json_decode($value['images'], TRUE) : array();
            }
        }

        return $result;
    }

    public function insert($data)
    {
        $gearId = $this->db->insertRowTable('r_gear', $data);
        if($gearId){
            $fields = ['gearId','name','shortDesc','gender','feature','price','brand','shoeCat','score','publishTime','isShow','likes'];
            $row = array_intersect_key($data,array_flip($fields));
            $row['gearId'] = $gearId;
            $row['brandIsShow'] = 1;
            $this->base->load('xunSearch')->init('gear')->addIndex($row);
        }
        return $gearId;
    }

    public function update($data)
    {
        $res = $this->db->updateRowTable('r_gear',$data);
        $fields = ['name','shortDesc','gender','feature','price','brand','shoeCat','score','publishTime','isShow','likes'];
        if(array_intersect_key($data,array_flip($fields)) && $res){
            $this->updateIndex($data['gearId']);
        }
        return $res;
    }

    public function updateIndex($gearId){
        $fields = ['name','shortDesc','gender','feature','price','brand','shoeCat','score','publishTime','isShow','likes'];
        $row = $this->db->getRowTable('r_gear',$fields,"gearId='{$gearId}'");
        $row['gearId'] = $gearId;
        $row['brandIsShow'] =1 ;
        $this->base->load('xunSearch')->init('gear')->updateIndex($row);
        return true;
    }

    public function insertBrand($data)
    {
        $brandId = $this->db->insertRowTable('r_gear_brand', $data);
        return $brandId;
    }

    public function updateBrand($data)
    {
        if(isset($data['isShow'])){
            $old_row = $this->db->getRowTable('r_gear_brand',['isShow'],"brandId='{$data['brandId']}'");
            $old_isShow = $old_row['isShow'];
        }
        $res = $this->db->updateRowTable('r_gear_brand', $data);
        /*
        if(isset($old_isShow) && $old_isShow != $data['isShow']){
            $rows = $this->db->getAll("SELECT `gearId`,`name`,`shortDesc`,`gender`,`feature`,`price`,`brand`,`shoeCat`,`score`,`publishTime`,`isShow`,`likes` FROM r_gear WHERE brand = '{$data['brandId']}'");
            $xunSearch = $this->base->load('xunSearch')->init('gear');
            foreach($rows as $row){
                $row['brandIsShow'] = $data['isShow'];
                $xunSearch->update($row);
            }
        }
        */

        return $res;
    }
    
    /*
     * 获得外链商品详情
     */
    public function getGoodsInfo($gear_id,$supplier_id){
        $redisKey = REDIS_PREFIX.'GearGoods_'.$gear_id.'_'.$supplier_id;
        $row = $this->redis->hgetall($redisKey);
        if(empty($row)){
            $sql = "select a.images,b.price,b.url,b.item_id,b.merchant from r_gear a inner join r_gear_channel b on a.goods_id = b.goods_id where b.supplier_id=$supplier_id and a.gearId = $gear_id limit 1";
            $row = $this->db->getRow($sql);
            $this->redis->hmset($redisKey,$row);
            $this->redis->expire($redisKey,120);
        }
        return $row;
    }

    /*
     * 从浏览器获取客户端版本
     */
    public function getWebviewVersion(){
        $vn = 0;
        $ua = explode(" ",$_SERVER['HTTP_USER_AGENT']);
        foreach ($ua as $v){
            if(strpos($v,'JoggersV1')!==false){//android
                $v = str_replace('JoggersV1','',$v);
                $vn = common::versionToNumber(str_replace('/','',$v));
            }else if(strpos($v,'JoggersV2')!==false){//ios
                $v = str_replace('JoggersV2/','',$v);
                $vn = common::versionToNumber(str_replace('/','',$v));
            }
        }
        return $vn;
    }


    /*
     * 获得装备渠道链接
     */
    public function getGoodsChannelUrlFromH5($gearInfo){
        $vn = 0;
        $ua = explode(" ",$_SERVER['HTTP_USER_AGENT']);
        foreach ($ua as $v){
            if(strpos($v,'JoggersV1')!==false){//android
                $v = str_replace('JoggersV1','',$v);
                $vn = common::versionToNumber(str_replace('/','',$v));
                $this->base->projectId = 1;
            }else if(strpos($v,'JoggersV2')!==false){//ios
                $v = str_replace('JoggersV2/','',$v);
                $vn = common::versionToNumber(str_replace('/','',$v));
                $this->base->projectId = 2;
            }
        }
        $plantform = $vn > 2910  ? 1 : 2;
        return $this->getGoodsChannelUrl($gearInfo, $plantform);
    }
    /*
     * 获得装备渠道链接
     */
    public function getGoodsChannelUrl($gearInfo,$plantform,$news_id=0){
        $taokePid = $this->base->projectId==1 ? $this->base->config['taoke_pid']['android'] : $this->base->config['taoke_pid']['ios'];
        if($this->base->projectId!=1){
            $taokePid = 'mm_115171196_13668714_56054343';
        }
        $url = "http://run.hupu.com/mobile";
        if($news_id!=0){
            $track = 'taokenewsdetail&id='.$news_id;
            $trackValue = $news_id;
        }else{
            $track = 'taokegeardetail&id='.$gearInfo['gearId'];    
            $trackValue = $gearInfo['gearId'];
        }
        
        if($plantform==1){
            //新版
            $url = "joggers://gear/channel/taobao?taokePid={$taokePid}&itemId={$gearInfo['item_id']}&msg=正在前往淘宝,请耐心等待";
        }else if($plantform==2){
            $gearInfo['url'] = urlencode($gearInfo['url']);
            //旧版
            $url = 'http://'.$this->base->config['host']."/show/geargoto?_track={$track}&_trackValue=$trackValue&merchant={$gearInfo['merchant']}&url={$gearInfo['url']}";
        }else if($plantform==3){
            //app外
            $url = "http://a.mlinks.cc/AaCS?news_id=$news_id";
        }
        return $url;
    }

    /*
     * 搜索建议
     */
    public function searchSuggest($keywords,$limit=10){
        $searcher = $this->base->load('xunSearch')->init('gear')->getSearcher();
        $searcher->setAutoSynonyms();
        $res = $searcher->setLimit($limit,0)->search("isShow:1 name:$keywords");
        $docs = [];
        foreach($res as $v){
           $gear = $this->getGearInfo($v['gearId']);
           if($gear['isShow']==1){
                $docs[] = [
                    'gear_id' => $v->gearId,
                    'name' => $searcher->highlight($v->name)
                ];
            }
        }
        return $docs;
    }

    /*
     * 获取数据
     */
    public function loadDataFromDB($redisKey, $sql){
        $redisKey = REDIS_PREFIX . $redisKey;
        $result = json_decode($this->redis->get($redisKey));

        if(empty($result)){
            $result =  $this->db->getAll($sql);
            $this->redis->set($redisKey,json_encode($result),600);
        }else{
            $result = (array)$result;
            foreach ($result as & $v) {
                $v = (array)$v;
            }
        }
        return $result;
    }


    /*
     * 获取类目
     */
    public function getGearCategory(){
        $sql = 'select catId,catName,logo from r_gear_cat where isShow=1 order by sorder asc';
        return $this->loadDataFromDB('GearCategoryList',$sql);
    }

    /*
     * 获取品牌
     */
    public function getGearBrand($catId){
        $query = empty($catId) ? '' : ' and catId='.$catId;
        $sql = "select brandId,brandName,logo from r_gear_brand where isShow=1 $query and brandId in (select distinct brand from r_gear where isShow=1 and type=0) order by sorder asc";
        return $this->loadDataFromDB('GearBrandList_'.$catId,$sql);
    }

    /*
     * 获取每日好价
     */
    public function getHomeBestGear(){
        $ids =  $this->redis->lrange(REDIS_PREFIX.'GearHomeBestGoods',0,7);
        $list = array();
        foreach ($ids as & $v) {
            $gear = $this->getGearInfo($v);
            $gear['min_price'] = $gear['price'];
            if(!empty($gear['goods_id'])) {
                $sql = "select min(price) as price from r_gear_channel where goods_id = {$gear['goods_id']} and status=1 and price >0 and merchant='淘宝' ";
                $gooditem = $this->loadDataFromDB('GearChannelMinPrice_' . $gear["goods_id"], $sql);
                if (!empty($gooditem)) {
                    $gear['min_price'] = $gooditem[0]['price'];
                }
            }
            $list[] = $gear;
        }
        return $list;
    }

    public function getSimilarGearRecommend($gearId, $catId, $limit){
        $sql = "select gearId from r_gear where catId = {$catId}  and isShow=1 and goods_id > 0 limit 200";   
        $ids =  $this->loadDataFromDB('GearSimilarRecommend_'.$catId, $sql);
        shuffle($ids);
        
        $list = array();
        if(!empty($ids)){
            foreach ($ids as & $v) {
                if($v['gearId']!=$gearId){
                    $gear = $this->getGearInfo($v['gearId']);
                    if(!empty($gear)){
                        $gear['image'] = count($gear['images'])>0?$gear['images'][0]:'';
                        $gear['shortDesc'] = strip_tags($gear['shortDesc']);
                        $list[] = $gear;
                    }
                    if(count($list)==$limit){
                        break;
                    }
                }
            }
        }
        return $list;
    }

    /*
     * 获取推荐的装备  
     */
    public function getHomeRecommendGear($page,$num=20){
        $page < 1 && $page = 1;
        $begin = ($page - 1) * $num;


        $redisKey = REDIS_PREFIX.'GearRecommendIds';
        $gearIdList = json_decode($this->redis->get($redisKey));

        if(empty($gearIdList)){
            $gearIdList = $this->db->getAll('select gearId from r_gear where type=0 and goods_id > 0  and isShow=1 limit 1000');
            $list = array();
            foreach ($gearIdList as & $v) {
                $list [] = $v['gearId'];
            }
            shuffle($list);
            $this->redis->set($redisKey,json_encode($list),600);
            $gearIdList = $list;
        }

        $gearIdList = array_slice($gearIdList, $begin,$num);

        $list = array();
        foreach ($gearIdList as & $v) {
            $gear = $this->getGearInfo($v);
            $gear['shortDesc'] = strip_tags($gear['shortDesc']);
            $list [] = $gear;
        }
        return $list;

    }

    /*
     * 获取帖子
     */
    public function getHomeNewsList($page,$sort=1,$num=10){
        $page < 1 && $page = 1;
        $begin = ($page - 1) * $num;

        $order = " order by b.add_time desc";
        if( $sort == 2) {
            $order = " order by b.loves desc";
        }

        $sql = "select a.news_id from r_boardpost a inner join r_news b on a.news_id =b.news_id where b.is_show = 1 and a.boardId = 'gearNews' $order";
        $newsIdList = $this->loadDataFromDB('GearNewsList_'.$sort,$sql);
        $newsIdList = array_slice($newsIdList, $begin,$num);

        $list = array();
        foreach ($newsIdList as & $v) {
            $newsInfo = $this->base->load('bbs')->getPostInfo($v['news_id']);
            $imgarray = array();
            if(!empty($newsInfo['sourceImg'])){
                $newsInfo['imginfo'] = json_decode($newsInfo['imginfo']);
                $thumb_img = $newsInfo['thumb_img'];

                for($x=0; $x<count($newsInfo['thumb_img']);$x++){
                    if($newsInfo['imginfo'][$x]->width >=400&&$newsInfo['imginfo'][$x]->height >=350){
                        $name = $newsInfo['sourceImg'][$x];
                        $arr = explode('_',$name);
                        $name = !empty($arr) ? $arr[1] : null;
                        $isFind = false;
                        if(!empty($name)){
                            foreach ($newsInfo['thumb_img'] as & $v) {
                                if(strrpos($v,$name)){
                                    $imgarray[] = $v;
                                    $isFind = true;
                                    break;
                                }
                            }
                        }
                        if(!$isFind){
                           $imgarray[] = $newsInfo['sourceImg'][$x];
                        }
                        if(count($imgarray)==4){
                            break;
                        }
                    }
                }
            }
            $newsInfo['hotvalue'] = $newsInfo['total_comment']*4 + $newsInfo['loves']*7;

            $newsInfo['thumb_img'] = $imgarray;
            $newsInfo['add_time'] = date('m-d',$newsInfo['add_time']);
            $list [] = $newsInfo;
        }

        return $list;
    }


    /*
     * 获取装备列表
     */
    public function getGearList($w,$catId, $sex, $price, $brand, $order, $page, $num=20){
        $query = " type=0  and isShow=1 ";
        $sort = ' order by viewCounts desc';

        if($order=='2'){
            $sort = " order by price asc ";
        }elseif($order=='3'){
            $sort = " order by price desc";
        }

        if(!empty($catId)){
            $query .= " and catId={$catId}";
        }

        if(!empty($sex)&&$sex!='3'){
            $query .= " and gender=$sex";
        }

        if(!empty($brand)){
            $query .= " and brand=$brand";
        }

        if(!empty($price)){
            $arr = explode('-',$price);
            $query .= " and price >= $arr[0]";
            if(count($arr)==2){
                $query .= " and price <=$arr[1]";
            }
        }


        if(!empty($w)){
            $w = substr(strip_tags(urldecode($w)),0,100);
            $docs = array();
            $searcher = $this->base->load('xunSearch')->init('gear')->getSearcher();
            $searcher->setAutoSynonyms();
            $res = $searcher->setLimit(1000,0)->search("isShow:1 name:$w");
            foreach($res as $v){
                $docs[] = $v->gearId;
            }
            $docs[] = '0';
            $ids = join(',', $docs);
            $query .= " and gearId in($ids)";
        }

        $page < 1 && $page = 1;
        $begin = ($page - 1) * $num;

        return $this->db->getAll("select gearId from r_gear where $query $sort limit {$begin},{$num}");
    }

    public function getGrouponByGearId($gearId){
        $sql = "select id from r_flash_sales where status in(0,5) and gear_id = $gearId limit 3 ";
        $result = $this->db->getAll($sql);
        if(!empty($result)){
            $out = array();
            foreach ($result as $v){
                $out[] =  $this->getGrouponDetail($v['id']);
            }
            return $out;
        }
        return null;
    }

    public function getGrouponDetail($id){
        $groupon = $this->base->load('flashBuy')->getFlashBuyInfo($id);
        if(!empty($groupon)){
             $groupon['num'] = $groupon['total_num']-$groupon['sale_num'];

             $groupon['current_time'] = time();
             $groupon['url']='';
             $groupon['num_msg']='';
             if($groupon['type']==2){
                $sql = "select item_id,'groupon' as merchant,url,$id as gearId from r_gear_shihuogroupon where groupon_id={$groupon['shihuo_grouponid']}";
                $row = $this->db->getRow($sql);

                $groupon['num'] = 9999;
                $groupon['url'] = $this->getGoodsChannelUrlFromH5($row);
             }
             if($groupon['status']==0){
                $groupon['end_time'] = $groupon['start_time'];
                $groupon['button'] = array('status_msg'=>'距开始','buy1'=>'敬请期待','buy2'=>'未开始','buy1_class'=>'bg_gray','buy2_class'=>'gray');
             }else if($groupon['status']==10){
                $groupon['button'] = array('status_msg'=>'已结束','buy1'=>'已结束','buy2'=>'已结束','buy1_class'=>'bg_gray','buy2_class'=>'gray');
             }else{
                 $groupon['button'] = array('status_msg'=>'距结束','buy1'=>'立即购买','buy2'=>'去抢购','buy1_class'=>'bg_red','buy2_class'=>'');
                 if($groupon['num']<=0){
                     $groupon['button']['buy1']='抢光了...';
                     $groupon['button']['buy1_class']='bg_gray';
                     $groupon['button']['buy2']='抢光了';
                     $groupon['button']['buy2_class']='gray';
                 }else{
                     $groupon['num_msg'] = '还剩'.$groupon['num'] .'件';
                 }
                 if(!empty($groupon['shihuo_grouponid'])){
                     $groupon['num_msg'] = '';
                 }
             }
             $groupon['images'] =  !empty($groupon['images']) ? json_decode($groupon['images']) : array();
             $groupon['image'] = !empty($groupon['images']) ? current($groupon['images']) : '';
             $groupon['express_fee'] = empty($groupon['express_fee']) ? 0 : $groupon['express_fee'];
        }
        //print_r($groupon);
        return $groupon;
    }

    public function getGrouponList($page,$order=1,$num=10){
        $query = " type in (1,2) and status in (0,5) ";
        $sort = "  order by `is_featured` desc , status desc,  type asc    ";

        if($order==2){
            $sort = " order by low_price asc";
        }else if($order==3){
            $sort = " order by low_price desc";
        }else if($order==4){
            $sort = " order by start_time desc";      
        }

        $page < 1 && $page = 1;
        $begin = ($page - 1) * $num;

        $sql = "select id from r_flash_sales where $query $sort limit {$begin},{$num}";
        $ids =  $this->db->getAll($sql);

        $result = array();
        foreach ($ids as $v) {
            $result[] = $this->getGrouponDetail($v['id']);
        }
        return $result;
    }

    /**
     * 购物车
     */
    public function addshopcart($uid,  $ogid,$num,$inshopcart)
    {
        $update_time = $this->base->time;

        $stand_good = $this->base->load('goods')->getObjectStandGoodsById($ogid);


        $stand_good_id =$stand_good['stand_good_id'];
        $flash_id =$stand_good['object_id'];
        //更新购物车数量
        if(empty($inshopcart)) {
            $old = $this->db->getRow("select * from r_gear_shopcart where uid=$uid and stand_good_id=$stand_good_id");
            if($this->base->load('goods')->checkStock($ogid,$num+$old['num'])<=0) {
                return -2;
            }
            if (!empty($old)) {
                return $this->db->update("update r_gear_shopcart set num=num+$num where uid=$uid and stand_good_id=$stand_good_id");
            }
        }

        $count  = $this->checkshopcount($uid);
        if($count>100){
            return -1;
        }

        if(!empty($stand_good_id)) {
            $cardArray = compact('uid', 'flash_id','stand_good_id', 'num', 'update_time');
            return $this->db->insertRowTable('r_gear_shopcart', $cardArray)>0 ? true : false;
        }else{
            return false;
        }
    }
    /**
     * 购物车
     */
    public function checkshopcount($uid){
        if(empty($uid)){
            return 0;
        }

        return $this->db->getOne("select count(0) from r_gear_shopcart where uid={$uid}");
    }

    /**
     * 购物车
     */
    public function delshopcart($uid, $ogid)
    {
        foreach (explode(',',$ogid) as $v) {
            $stand_good = $this->base->load('goods')->getObjectStandGoodsById($v);
            $this->db->delDataTable("r_gear_shopcart", "uid={$uid} and stand_good_id={$stand_good['stand_good_id']}");
        }
        return true;
    }

    /**
     * 购物车列表
     */
    public function shopcartlist($uid)
    {
        $carts = $this->db->getAll("select flash_id,stand_good_id,num from r_gear_shopcart where uid={$uid}");

        $canBuyList = array();
        $nocanBuyList = array();
        foreach ($carts as $v){
            $v['good_object']  = $this->base->load('goods')->getObjectGoodsId($v['stand_good_id'],$v['flash_id']);
            $v['flash_object'] = $this->getGrouponDetail($v['flash_id']);
            if($v['good_object']['status']!=0) {
                $v['flash_object']['status']=10;
            }

            $v['good_object']['num'] = $v['good_object']['stock_num'] - $v['good_object']['sale_num'];
            $v['image'] = current($v['good_object']['atrr'])['img_source'];
            if (empty($v['image'])) {
                $v['image'] = $v['flash_object']['image'];
            }
            if($v['flash_object']['status']!=5){
                $nocanBuyList[] = $v;
            }else{
                $canBuyList[] = $v;
            }
        }
        return array_merge($canBuyList,$nocanBuyList);
    }

    /**
     * 获取海淘商品信息
     */
    public function gethaitaodetail($id){
        $sql = "select * from r_gear_shihuohaitao where haitao_id=$id ";
        return $this->db->getRow($sql);
    }

    /*
     * 封装商品信息 补充未添的sku为0
     */
    public function wrappergoodsinfo($id){
        $childGoods = $this->base->load('goods')->getFlashGoodsList($id);
        foreach($childGoods as $key=>$goods){
            $arrAttr = $this->base->load('goods')->getAllAttrByPid($goods['product']['id']);
            sort($arrAttr);
            $childGoods[$key]['attrs'] = $arrAttr;
        }
        $goods = current((array)$childGoods);

        if(!empty($goods)) {
            //补充未添的sku为0
            $attr = array();
            foreach ($goods['attrs'] as $item) {
                $tmp = array();
                foreach ($item['attrValue'] as $v) {
                    $tmp[] = array($v['id'] => $v['title']);
                }
                $attr[] = $tmp;
            }
            if(count($attr)>1) {
                $r = $this->base->load('goods')->getDescartes($attr);
                $all = array();
                foreach ($r as $item) {
                    $tmp = array();
                    foreach ($item as $v) {
                        $tmp[key($v)] = $v[key($v)];
                    }
                    $all[implode('—', array_keys($tmp))] = implode('—', array_values($tmp));
                }
                foreach ($goods['childGoods'] as $v) {
                    $id = $v['attrPathId'];
                    if (array_key_exists($id, $all)) {
                        unset($all[$id]);
                    }
                }
                foreach ($all as $key => $value) {
                    $goods['childGoods'][] = array(
                        'attrPathName' => $value,
                        'attrPathId' => $key,
                        'stockNum' => 0,
                        'saleNum' => 0,
                        'id' => '',
                    );
                }
            }
        }
        return $goods;

    }

    /*
     * 获取用户身份证
     */
    public function getUserCardId($uid){
        if(empty($uid)){
            return null;
        }
        return $this->db->getOne("select cardid from r_user_ext where uid=$uid");
    }

    /*
     * 获取淘宝渠道数据
     */
    public function getTaobaoChannel($id){
        if($id==''){
            return null;
        }
        return $this->db->getRow("select * from r_gear_channel where id=".$id." and status=1");
    }


}
